package com.example.graphic.AI;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 图片生成文案AI客户端实现
 */
@Slf4j
@Component
public class ImageDescriptionClient implements AIClient<ImageDescriptionRequest, ImageDescriptionResponse> {
    
    private static final String API_URL = "http://192.168.1.200:8998/generate";
    private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
    
    private final OkHttpClient httpClient;
    private final ObjectMapper objectMapper;
    
    @Autowired
    public ImageDescriptionClient(OkHttpClient httpClient, ObjectMapper objectMapper) {
        this.httpClient = httpClient;
        this.objectMapper = objectMapper;
    }
    
    @Override
    public ImageDescriptionResponse execute(ImageDescriptionRequest request) {
        // 验证请求参数
        if (!request.validate()) {
            log.error("无效请求: 必要参数为空");
            throw new IllegalArgumentException("图片URL、风格、标签、提示词和用户ID不能为空");
        }
        
        try {
            // 构建请求体 - 直接使用请求对象
            String jsonBody = objectMapper.writeValueAsString(request);
            RequestBody body = RequestBody.create(jsonBody, JSON);
            
            // 构建HTTP请求
            Request httpRequest = new Request.Builder()
                    .url(API_URL)
                    .post(body)
                    .addHeader("Content-Type", "application/json")
                    .build();
            
            log.info("发送图片生成文案请求到: {}，请求体:{}", API_URL,httpRequest);
            
            // 执行请求
            try (Response response = httpClient.newCall(httpRequest).execute()) {
                String responseBody = response.body() != null ? response.body().string() : "";
                
                if (!response.isSuccessful()) {
                    log.error("HTTP请求失败，状态码: {}, 响应体: {}", response.code(), responseBody);
                    throw new RuntimeException("HTTP请求失败: " + response.code() + " " + response.message());
                }
                
                // 解析响应
                ImageDescriptionResponse descriptionResponse = objectMapper.readValue(responseBody, ImageDescriptionResponse.class);
                log.info("图片生成文案请求完成成功");
                
                return descriptionResponse;
            }
            
        } catch (IOException e) {
            log.error("图片生成文案请求网络错误", e);
            throw new RuntimeException("网络错误: " + e.getMessage(), e);
        } catch (Exception e) {
            log.error("图片生成文案请求意外错误", e);
            throw new RuntimeException("图片生成文案请求失败: " + e.getMessage(), e);
        }
    }
}